const Message = require('../models/Message');
const User = require('../models/User');
const Application = require('../models/Application');
const { Op } = require('sequelize');
const { sendMessageNotification } = require('../services/notification.service');

// 发送消息
exports.sendMessage = async (req, res) => {
  try {
    const { receiverId, applicationId, content } = req.body;
    const senderId = req.user.id;

    // 验证接收者是否存在
    const receiver = await User.findByPk(receiverId);
    if (!receiver) {
      return res.status(404).json({
        success: false,
        message: '接收用户不存在'
      });
    }

    // 如果关联了职位申请，验证申请是否存在
    if (applicationId) {
      const application = await Application.findByPk(applicationId);
      if (!application) {
        return res.status(404).json({
          success: false,
          message: '职位申请不存在'
        });
      }
    }

    // 创建消息
    const message = await Message.create({
      senderId,
      receiverId,
      applicationId: applicationId || null,
      content
    });

    // 发送消息通知
    await sendMessageNotification(receiverId, senderId, message.id);

    return res.status(201).json({
      success: true,
      message: '消息发送成功',
      data: message
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，发送消息失败',
      error: error.message
    });
  }
};

// 获取用户收到的消息
exports.getReceivedMessages = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 20, unreadOnly = false } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = { receiverId: userId };

    // 只看未读消息
    if (unreadOnly === 'true') {
      whereClause.isRead = false;
    }

    const { count, rows: messages } = await Message.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'Sender',
          attributes: ['id', 'name', 'email', 'role', 'companyId']
        },
        {
          model: Application,
          attributes: ['id', 'jobId', 'status']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    return res.status(200).json({
      success: true,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      data: messages
    });
  } catch (error) {
    console.error('获取收到的消息失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取收到的消息失败',
      error: error.message
    });
  }
};

// 获取用户发送的消息
exports.getSentMessages = async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;

    const { count, rows: messages } = await Message.findAndCountAll({
      where: { senderId: userId },
      include: [
        {
          model: User,
          as: 'Receiver',
          attributes: ['id', 'name', 'email', 'role', 'companyId']
        },
        {
          model: Application,
          attributes: ['id', 'jobId', 'status']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    return res.status(200).json({
      success: true,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
      data: messages
    });
  } catch (error) {
    console.error('获取发送的消息失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取发送的消息失败',
      error: error.message
    });
  }
};

// 标记消息为已读
exports.markAsRead = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const message = await Message.findOne({
      where: {
        id,
        receiverId: userId
      }
    });

    if (!message) {
      return res.status(404).json({
        success: false,
        message: '消息不存在或无权操作'
      });
    }

    await message.update({ isRead: true });

    return res.status(200).json({
      success: true,
      message: '消息已标记为已读',
      data: message
    });
  } catch (error) {
    console.error('标记消息为已读失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，标记消息为已读失败',
      error: error.message
    });
  }
};

// 删除消息
exports.deleteMessage = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 只能删除自己发送或接收的消息
    const message = await Message.findOne({
      where: {
        id,
        [Op.or]: [
          { senderId: userId },
          { receiverId: userId }
        ]
      }
    });

    if (!message) {
      return res.status(404).json({
        success: false,
        message: '消息不存在或无权操作'
      });
    }

    await message.destroy();

    return res.status(200).json({
      success: true,
      message: '消息已删除'
    });
  } catch (error) {
    console.error('删除消息失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，删除消息失败',
      error: error.message
    });
  }
};

// 获取未读消息数量
exports.getUnreadCount = async (req, res) => {
  try {
    const userId = req.user.id;

    const count = await Message.count({
      where: {
        receiverId: userId,
        isRead: false
      }
    });

    return res.status(200).json({
      success: true,
      data: { unreadCount: count }
    });
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取未读消息数量失败',
      error: error.message
    });
  }
};